package com.ibpd.shopping.web.controller.shopInterface;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.util.AlipayNotify;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.common.TxtUtil;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.entity.OrderEntity;
import com.ibpd.shopping.entity.OrderTmpEntity;
import com.ibpd.shopping.entity.OrderpayEntity;
import com.ibpd.shopping.service.order.IOrderService;
import com.ibpd.shopping.service.order.OrderServiceImpl;
import com.ibpd.shopping.service.orderpay.IOrderpayService;
import com.ibpd.shopping.service.orderpay.OrderpayServiceImpl;
import com.ibpd.shopping.service.ordertmp.IOrderTmpService;
import com.ibpd.shopping.service.ordertmp.OrderTmpServiceImpl;
@Controller
public class Inter_Alipay  extends BaseController{
	@RequestMapping("notify.do")
	public void notify(HttpServletRequest request,HttpServletResponse resp) throws Exception{
		//获取支付宝GET过来反馈信息  
	    Map<String,String> params = new HashMap<String,String>();  
	    Map requestParams = request.getParameterMap();  
	    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {  
	        String name = (String) iter.next();  
	        String[] values = (String[]) requestParams.get(name);  
	        String valueStr = "";  
	        for (int i = 0; i < values.length; i++) {  
	            valueStr = (i == values.length - 1) ? valueStr + values[i]  
	                    : valueStr + values[i] + ",";  
	        }  
	        //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化  
	       // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");  
	        params.put(name, valueStr);  
	    }  
	  
	      //做日志记录
	    StringBuffer sb=new StringBuffer();
	    for(String key:params.keySet()){
	    	sb.append(key+"="+params.get(key)+"\r\n");
	    } 
	    TxtUtil.writeTxtFile(sb.toString(), new File(request.getRealPath(SysUtil.getUploadFileBaseDir())+File.separatorChar+"alipay.txt"));
	    //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//  
	    String trade_no = request.getParameter("trade_no");             //支付宝交易号  
	    String order_no = request.getParameter("out_trade_no");         //获取订单号  
	    String total_fee = request.getParameter("total_fee");           //获取总金额  
	    String subject = request.getParameter("subject");//new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");//商品名称、订单名称  
	    String body = "";  
	    if(request.getParameter("body") != null){  
	        body = request.getParameter("body");//new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");//商品描述、订单备注、描述  
	    }  
	    String buyer_email = request.getParameter("buyer_email");       //买家支付宝账号  
	    String trade_status = request.getParameter("trade_status");     //交易状态  
	    IbpdLogger.getLogger(this.getClass()).info("trade_no="+trade_no+"\nout_trade_no="+order_no+"\ntotal_fee"+total_fee+"\nsubject"+subject+"\nbody="+body+"\nbuyer_email"+buyer_email+"\ntrade_status="+trade_status);
	    //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//  
	      
	    //计算得出通知验证结果  
	    boolean verify_result = AlipayNotify.verify(params);  
	        //说的打工阿萨德发的双方都发大水发大水分 
	    if(verify_result){//验证成功  但是放松放松的地方   
	        //////////////////////////////////////////////////////////////////////////////////////////  
	        //请在这里加上商户的业务逻辑程序代码  
	  
	        if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){  
	            //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）  
	                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序  
	                //如果有做过处理，不执行商户的业务程序  
		    IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
        	if(order_no.substring(0,2).equals("m_")){
	        		IOrderTmpService tmpServ=(IOrderTmpService) getService(OrderTmpServiceImpl.class);
	        		IOrderpayService payServ=(IOrderpayService) getService(OrderpayServiceImpl.class);
	        		List<OrderTmpEntity> tmpList=tmpServ.getOrderTmpList(order_no);
	        		if(tmpList!=null){
	        			for(OrderTmpEntity tmp:tmpList){ 
	    			        List<OrderEntity> ordList=orderServ.getList("from "+orderServ.getTableName()+" where id="+tmp.getOrderId(), null);
	    			        if(ordList!=null){ 
	    			        	if(ordList.size()>0){
	    				        	OrderEntity order=ordList.get(0);
	    				        	order.setPaystatus(OrderEntity.order_paystatus_y);
	    				        	order.setStatus(OrderEntity.order_status_pass);
//	    				        	order.setPayType(OrderEntity.)
	    				        	orderServ.saveEntity(order);
//	    				        	orderServ.getDao().clearCache();
	    				        	OrderpayEntity pay=payServ.getOrderpayByOrderId(order.getId());
	    				        	if(pay!=null){
	    				        		pay.setPaystatus(OrderEntity.order_paystatus_y);
	    				        		payServ.saveEntity(pay);
//	    				        		payServ.getDao().clearCache();
	    				        	}
	    			        	}
	    			        }	        				
	        			}
	        		}
	        	}else{
			        List<OrderEntity> ordList=orderServ.getList("from "+orderServ.getTableName()+" where orderNumber="+order_no, null);
			        if(ordList!=null){ 
			        	if(ordList.size()>0){
				        	OrderEntity order=ordList.get(0);
				        	order.setPaystatus(OrderEntity.order_paystatus_y);
				        	order.setStatus(OrderEntity.order_status_pass);
//				        	order.setPayType(OrderEntity.)
				        	orderServ.saveEntity(order);
			        	}
			        }	        		
	        	}
	        }  
	        if(1==1){
	        	Integer o=0;
	        }
	        //该页面可做页面美工编辑  
	        IbpdLogger.getLogger(this.getClass()).info("验证成功<br />");  
	        IbpdLogger.getLogger(this.getClass()).info("trade_no=" + trade_no);  
	        //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——  
	  
	        //////////////////////////////////////////////////////////////////////////////////////////  
	    }else{  
	        //该页面可做页面美工编辑  
	    	IbpdLogger.getLogger(this.getClass()).info("验证失败");  
	    }  
	}
	public static void main(String[] a){
//		String order_no="m_2015030766277";
//		IOrderTmpService tmpServ=(IOrderTmpService) ServiceProxyFactory.getServiceProxy(OrderTmpServiceImpl.class);
//		List<OrderTmpEntity> tmpList=tmpServ.getOrderTmpList(order_no);
//		IbpdLogger.getLogger(this.getClass()).info(tmpList.size());
	}
}
